/*
 * SD_New_groupViewController
 * @description 本文件提供相册指定好友(我的分组)分组界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供相册指定好友(我的分组)分组界面的ViewController
 */

#import "SD_New_groupViewController.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "ExampleNestedTablesViewController.h"
#import "ViewController.h"
#import "UICheckBox.h"
#import "BanBu_NavigationController.h"
#define ROW_INDEX 112411
@interface SD_New_groupViewController ()
{
    //右上角保存按钮，需要变化
    UIButton * _saveBu;
}
@end

@implementation SD_New_groupViewController
@synthesize preSelectedGroup = _preSelectedGroup;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [_preSelectedGroup release];
    _preSelectedGroup = nil;
    [self.selectArr release];
    [self.datArr release];
    self.selectGroupCallBack = nil;
    [super dealloc];
}
-(void)viewWillAppear:(BOOL)animated
{
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = UIColorWithRGB(237, 239, 241, 1.0);
    self.title = NSLocalizedString(@"Competence_MyGroup", 我的分组);
    self.selectArr = [[NSMutableArray alloc]initWithCapacity:1];
    [self.selectArr addObjectsFromArray:self.preSelectedGroup];
    
    self.datArr = [[NSMutableArray alloc]initWithCapacity:1];
    tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height-44) style:UITableViewStylePlain];
    tableview.backgroundColor = UIColorWithRGB(237, 239, 241, 1.0);
    tableview.backgroundView = nil;
    tableview.delegate = self;
    tableview.dataSource = self;
    tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableview];
    [self SetBarButtonItem];

    UIView * bgview = [[UIView alloc]init];
    [self.view addSubview:bgview];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 70)];
    footerView.backgroundColor = [UIColor whiteColor];
    UIView * toolV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 24)];
    toolV.backgroundColor = UIColorWithRGB(237, 239, 241, 1.0);
    [footerView addSubview:toolV];
    [toolV release];
    UIImageView * lineV1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"addline.png"]];
    [lineV1 setFrame:CGRectMake(0, 23.5, 320, 0.5)];
    [footerView addSubview:lineV1];
    [lineV1 release];
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(10, 27, 300, 36);
    UIImageView * newGroupAdd = [[UIImageView alloc]initWithFrame:CGRectMake(15, 10, 18, 18)];
    newGroupAdd.image = [UIImage imageNamed:@"newGroupAdd.png"];
    [searchBtn addSubview:newGroupAdd];
    [newGroupAdd release];
    UILabel * newGroupLa = [[UILabel alloc]initWithFrame:CGRectMake(40, 4, 220, 26)];
    newGroupLa.text = NSLocalizedString(@"Competence_NewGroup", 新建分组);
    [searchBtn addSubview:newGroupLa];
    newGroupLa.backgroundColor = [UIColor clearColor];
    newGroupLa.font = [UIFont systemFontOfSize:16.0];
    [newGroupLa release];
    [searchBtn setBackgroundImage:[UIImage imageNamed:@"great_section.png"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(clickOK) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:searchBtn];
    UIImageView * lineV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"addline.png"]];
    [lineV setFrame:CGRectMake(0, 69.5, 320, 0.5)];
    [footerView addSubview:lineV];
    [lineV release];
    
    tableview.tableHeaderView = footerView;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createOrDeleteGroup:) name:@"refreshView" object:nil];
}

#pragma mark - 创建新的分组直接选中
- (void)createOrDeleteGroup:(NSNotification *)notification
{
    NSDictionary * groupDict = [notification object];
    if ([[groupDict valueForKey:@"action"] isEqualToString:@"create"])
    {
        [self.selectArr addObject:[groupDict valueForKey:@"title"]];
    }
    else
    {
        [self.selectArr removeObject:[groupDict valueForKey:@"title"]];
    }
    //当没有选中分组时，保存按钮不能点击
    if (self.selectArr.count == 0)
    {
        [_saveBu setTitleColor:UIColorWithRGB(255, 255, 255, 0.5) forState:UIControlStateNormal];
        _saveBu.userInteractionEnabled = NO;
    }
    else
    {
        [_saveBu setTitleColor:UIColorWithRGB(255, 255, 255, 1.0) forState:UIControlStateNormal];
        _saveBu.userInteractionEnabled = YES;
    }

    [AppComManager getBanBuData:BanBu_Get_Friendgroup_Ofmy par:nil delegate:self];
}

//-(void)viewWillDisappear:(BOOL)animated
//{
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"refreshView" object:nil];
//}

//刷新分组列表
-(void)viewWillLayoutSubviews
{
    [AppComManager getBanBuData:BanBu_Get_Friendgroup_Ofmy par:nil delegate:self];
}

#pragma mark 初始化Barbutton
-(void)SetBarButtonItem
{
    _saveBu = [UIButton buttonWithType:UIButtonTypeCustom];
    [_saveBu setTitle:NSLocalizedString(@"saveButton", 保存) forState:UIControlStateNormal];
    [_saveBu setFrame:CGRectMake(0, 0, 60, 35)];
    [_saveBu setTitleColor:UIColorWithRGB(255, 255, 255, 0.5) forState:UIControlStateNormal];
    _saveBu.userInteractionEnabled = NO;
    _saveBu.titleLabel.font = [UIFont systemFontOfSize:16.0];
    [_saveBu addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * saveItem = [[UIBarButtonItem alloc]initWithCustomView:_saveBu];
    self.navigationItem.rightBarButtonItem = saveItem;
}

#pragma mark 点击事件 - 新建分组
-(void)clickOK
{
    ExampleNestedTablesViewController * evc = [[ExampleNestedTablesViewController alloc]init];
    BanBu_NavigationController *nav = [[BanBu_NavigationController alloc] initWithRootViewController:evc];
    
    [self GetCurrenTimeFromGroupname];
    [self presentViewController:nav animated:YES];
//    [self presentModalViewController:nav animated:YES];
    [evc release];
    evc = nil;
    [nav release];
    nav = nil;
}

-(void)save
{
    NSLog(@"保存成功");
    NSLog(@"%@",self.selectArr);
    
    //修改：yinlinlin:将选中的分组传到上一界面
    if (self.selectGroupCallBack)
    {
        self.selectGroupCallBack(self.selectArr);
    }
    //修改完成：yinlinlin
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//    if(_datArr.count)
//    {
//        return [[self.datArr objectAtIndex:0] count];
//    }
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    return 1;
    if(_datArr.count)
    {
        return [[self.datArr objectAtIndex:0] count];
    }
    return 0;
}

-(SD_New_group*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"SD_New_group";
    SD_New_group  * cell = (SD_New_group *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell= (SD_New_group *)[[[NSBundle  mainBundle]  loadNibNamed:@"SD_New_group" owner:self options:nil]  lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
        if (self.datArr.count >0)
        {
            NSArray * groupArr = [self.datArr objectAtIndex:indexPath.section];
            [cell.selectbtn addTarget:self action:@selector(selectPress:) forControlEvents:UIControlEventTouchUpInside];
            cell.selectbtn.tag = indexPath.row + ROW_INDEX;
            //修改：yinlinlin
            NSString * groupTitle = [groupArr objectAtIndex:indexPath.row];
            
            if ([self.selectArr indexOfObject:groupTitle] == NSNotFound)
            {
                [cell.selectbtn setSelected:NO];
            }
            else
            {
                [cell.selectbtn setSelected:YES];
            }
            NSString * grouplist = [[self.datArr objectAtIndex:indexPath.section+1] objectAtIndex:indexPath.row];
            //添加分组联系人为0的情况的判断，2014年08月29日18:02:18
            if (grouplist.length > 1)
            {
                cell.GruopName.text =[NSString stringWithFormat:@"%@(%d)",groupTitle,[[grouplist componentsSeparatedByString:@","] count]];
                
            }
            else
            {
                cell.GruopName.text =[NSString stringWithFormat:@"%@(0)",groupTitle];
            }
            
            if (indexPath.row < groupArr.count - 1)
            {
                [cell.lineImgV setFrame:CGRectMake(20, 45.5, 300, 0.5)];
            }
            else
            {
                [cell.lineImgV setFrame:CGRectMake(0, 45.5, 320, 0.5)];
            }
    }
    return cell;
}

//当前选择组
-(void)selectPress:(UIButton *)sender
{
    if([self.selectArr indexOfObject:[[self.datArr objectAtIndex:0] objectAtIndex:sender.tag - ROW_INDEX]] != NSNotFound)
    {
        [self.selectArr removeObject:[[self.datArr objectAtIndex:0] objectAtIndex:sender.tag - ROW_INDEX]];
    }
    else
    {
        [self.selectArr addObject:[[self.datArr objectAtIndex:0] objectAtIndex:sender.tag - ROW_INDEX]];
    }
    //当没有选中分组时，保存按钮不能点击
    if (self.selectArr.count == 0)
    {
        [_saveBu setTitleColor:UIColorWithRGB(255, 255, 255, 0.5) forState:UIControlStateNormal];
        _saveBu.userInteractionEnabled = NO;
    }
    else
    {
        [_saveBu setTitleColor:UIColorWithRGB(255, 255, 255, 1.0) forState:UIControlStateNormal];
        _saveBu.userInteractionEnabled = YES;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view point:self.view.center title:NSLocalizedString(@"loadingNotice", nil) activityAnimated:YES];
    self.navigationController.view.userInteractionEnabled = NO;


    [AppComManager getBanBuData:BanBu_Get_Friendlist_Bygroup par:[NSDictionary dictionaryWithObjectsAndKeys:[[self.datArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row],@"groupname",nil] delegate:self];
    self.groupname=[[self.datArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    MyAppDataManager.SelectGroupName = [[self.datArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 46;
}

-(void)GetCurrenTimeFromGroupname//根据当前时间命名分组
{
    NSInteger hour,min,sec;
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *now = [NSDate date];;
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    comps = [calendar components:unitFlags fromDate:now];
    hour = [comps hour];
    min = [comps minute];
    sec = [comps second];
    MyAppDataManager.SelectGroupName = [NSString stringWithFormat:@"%d%d%d",hour,min,sec];
}

- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
//    NSLog(@"%@",resDic);
    if(error)
    {
        
    }
    else
    {
        if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Friendgroup_Ofmy])
        {
            if([[resDic valueForKey:@"ok"] boolValue])//获取分组成功
            {
                [self.datArr removeAllObjects];
                NSArray * pname = [NSArray arrayWithObject:[[resDic valueForKey:@"list"]valueForKey:@"pname"]];
                NSArray * uidlist = [NSArray arrayWithObject:[[resDic valueForKeyPath:@"list"]valueForKeyPath:@"uidlist"]];
                [self.datArr addObjectsFromArray:pname];
                [self.datArr addObjectsFromArray:uidlist];
                [tableview reloadData];
            }
        }
        
        if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Friendlist_Bygroup])//获取分组详细信息成功
        {
            if([[resDic valueForKey:@"ok"] boolValue])
            {
                //修改：yinlinlin
                //因为在ViewController，更改原来的分组时，显示的数据类型不统一，所以改为model类型
                NSMutableArray * modelArr = [[NSMutableArray alloc]initWithCapacity:10];
                for (NSDictionary * userDict in [resDic valueForKey:@"list"])
                {
                    BanBu_UserModel * userModel = [[BanBu_UserModel alloc]init];
                    userModel.user_id = [userDict valueForKey:@"userid"];
                    userModel.face_url = [[userDict valueForKey:@"userinfor"] valueForKey:@"uface"];
                    userModel.gender = [[userDict valueForKey:@"userinfor"] valueForKey:@"gender"];
                    userModel.pname = [[userDict valueForKey:@"userinfor"] valueForKey:@"pname"];
                    [modelArr addObject:userModel];
                    [userModel release];
                }
                ViewController * vvc = [[ViewController alloc]initWithPersonDataArray:modelArr];
                [modelArr release];
                vvc.superior = @"group";
                NSLog(@"self.groupname:%@",self.groupname);
                vvc.groupname = self.groupname;
                self.navigationController.view.userInteractionEnabled = YES;
                [TKLoadingView dismissTkFromView:self.navigationController.view animated:YES afterShow:0];
                [self.navigationController pushViewController:vvc animated:YES];
                [vvc release];
                vvc = nil;
            }
        }
    }
}


@end
